package exo2;

import java.io.PrintWriter;
import java.util.*;
import java.util.Map.Entry;

public class Vendeur {
	String nom;
	HashMap<Integer, Integer> vehicules;

	public Vendeur(){
		vehicules = new HashMap<Integer, Integer>();
	}
	
	public Vendeur(String nom)
	{
		this.nom = nom;
		vehicules = new HashMap<Integer, Integer>();
	}
	
	public void readData(Scanner in) {
		String line = in.nextLine();
		StringTokenizer st = new StringTokenizer(line,"|");
		this.setNom(st.nextToken());
		
		while (st.hasMoreTokens())
		{
			vehicules.put(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
		}
		
		/*
		 * PREMIERE VERSION 
		 * 		
		String[] tokens = line.split("\\|");
		this.setNom(tokens[0]);
		
		for(int i = 1; i < tokens.length; i=i+2)
		{
			vehicules.put(Integer.parseInt(tokens[i]), Integer.parseInt(tokens[i+1]));
		}
		
		*/
	}

	public void writeData(PrintWriter out) {
		String s = this.getNom();
		for (Entry<Integer, Integer> entry : this.vehicules.entrySet()) {
			s = s + "|" + entry.getKey() + "|" + entry.getValue();
		}
		out.write(s+"\n");
		//PrintWriter est un buffer, donc flush.
		out.flush();
	}

	/**
	 * ajoute un vehicule dans l'inventaire du vendeur
	 * @param id id du vehicule
	 * @param nombre nombre d'exemplaire du vehicule
	 */
	public void ajouterVehicule(int id, int nombre){
		
		if(this.vehicules.containsKey(id))
			this.vehicules.put(id, this.vehicules.get(id)+nombre);
		else
			this.vehicules.put(id, nombre);		
	}
	
	public boolean equals(Object o){
		if (!(o  instanceof Vendeur))
			return false;
		
		boolean bool = false;
		Vendeur temp = (Vendeur) o;
		
		if(temp.getNom().equals(this.getNom()))
		{
			if(this.vehicules.equals(temp.vehicules))
			{
				bool = true;
			}
		}
		else
		{
			bool = false;
		}
		return bool;
	}
	
	public String toString()
	{
		String s = getNom();
		for (Entry<Integer, Integer> entry : vehicules.entrySet()) {
			s = s + "|" + entry.getKey() + "|" + entry.getValue();
		}
		return s;
	}
	
	public String getNom() {
		return this.nom;
	}

	public void setNom(String nom) {
		this.nom = nom;
	}
}
